/*
 * =====================================================================================
 *
 *       Filename:  linkedlist.c
 *
 *    Description:  reverse and combine linkedlist
 *
 *        Version:  1.0
 *        Created:  2012年03月29日 09时42分29秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Regan (), lcqhigh@gmail.com
 *        Company:  
 *
 * =====================================================================================
 */

#include	<stdio.h>
#include	<string.h>
#include	<stdlib.h>
#include	<assert.h>
#include	"utility.h"

#define	T int			/*  */

typedef struct LinkedNode_s
{
    T data;
    struct LinkedNode_s *next;
}LinkedNode;

LinkedNode *reverseLinkedList(LinkedNode *list)
{
    if (list)
    {
        LinkedNode *p = list->next;
        LinkedNode *prev = list;
        LinkedNode *pnext = NULL;
        while (p != NULL)
        {
            pnext = p->next;
            p->next = prev;
            prev = p;
            p = pnext;
        }
        list->next = NULL;
        list = prev;
    }
    return list;
}

void testReverse()
{
    int x[20];
    int times = 100;
    while (times--)
    {
        int nodecnt = rand() % 20 + 1;
        genRandInt(x, nodecnt);
        printf ( ">>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" );
        printIntarr(x, nodecnt);
        LinkedNode *listNodeArr = malloc(sizeof(LinkedNode) * (nodecnt+1)); 
        assert(listNodeArr != NULL);
        int i;
        for (i = 0; i < nodecnt; ++i)
        {
            listNodeArr[i].data = x[i];
            listNodeArr[i].next = &listNodeArr[i+1];
        }
        listNodeArr[nodecnt-1].next = NULL;
        LinkedNode *listHead = &listNodeArr[0];
        listHead = reverseLinkedList(listHead);
        printf ( "-----------------------------\n" );
        while (listHead)
        {
            printf ( "%d  ", listHead->data);
            assert(listHead->data == x[--i]);
            listHead = listHead->next;
        }
        assert(i == 0);
        free(listNodeArr);
        printf ( "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" );
    }
}


int main(int argc, char *argv[])
{
    testReverse();

    signed char c = -128;
    signed char d = c -1;
    printf ( "signed:%d, unsigned:%u, hex:%02x\n", d, d, d);
    return  0;
}
